package com.example.business;

import com.example.data.mapper.FileSourceMapper;
import com.example.data.model.FileSource;
import com.example.page.Page;
import com.example.page.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * Created by hldev on 17-2-15.
 */
@Service
public class FileSourceService {

    @Autowired
    private final FileSourceMapper fileSourceMapper;

    @Autowired
    private final UserService userService;

    public FileSourceService(FileSourceMapper fileSourceMapper, UserService userService) {
        this.fileSourceMapper = fileSourceMapper;
        this.userService = userService;
    }


    public Optional<FileSource> findById(Long id) {
        return Optional.ofNullable(fileSourceMapper.findById(id));
    }

    public List<FileSource> findAll() {
        return fileSourceMapper.findAll();
    }

    public Page<FileSource> findPage(Pageable pageable, String fileName, String createName, Integer status, String beginDate, String endDate) {
        pageable.addSomeParam("fileName", fileName)
                .addSomeParam("createName", createName)
                .addSomeParam("beginDate", beginDate)
                .addSomeParam("endDate", endDate)
                .addSomeParam("status", status);

        List<FileSource> list = fileSourceMapper.findPage(pageable);
        return new Page<>(pageable, list);
    }

    public void createFile(FileSource fileSource) {
//        Optional<AuthToken> authToken = AuthToken.getFromThreadLocal();
//        String x = AuthToken.getFromThreadLocal().get().userName;
//        fileSource.setCreateBy(x);
        fileSource.setDownloads(0);
//        fileSource.setCreateDate(LocalDateTime.now());
//        String orgId = userService.findById(AuthToken.getFromThreadLocal().get().ownerId).get().getOrgId();
//        fileSource.setOrgId(orgId);
        fileSourceMapper.create(fileSource);
    }

    @Transactional
    public void updateFile(FileSource fileSource) {
        fileSourceMapper.update(fileSource);
    }

    public void deleteFile(Integer id) {
        fileSourceMapper.delete(id);
    }
}
